<template>
	<div class="table-container layout-padding">
		<div class="table-padding layout-padding-view layout-padding-auto">
			<HTableControl
				:config="state.tableState.config"
				:header="state.tableState.header"
				:selectedRows="state.tableState.selectedRows"
				:tableSearch="state.tableSearch"
				@sort="sortHeader => (state.tableState.header = sortHeader)"
				@search="onTableSearch"
				@refresh="
					() => {
						initTableData();
						initTreeData();
					}
				"
			>
				<template v-slot:operationBtn>
					<el-button type="success" @click="onTableUpdate('add')">添加角色</el-button>
					<!-- <el-button type="danger" :disabled="state.tableState.selectedRows.length === 0">批量禁用</el-button> -->
				</template>
			</HTableControl>
			<HTable
				class="h-table"
				v-model:selectedRows="state.tableState.selectedRows"
				:config="state.tableState.config"
				:header="state.tableState.header"
				:data="state.tableState.data"
				:pageNum="state.params.page"
				:pageSize="state.params.limit"
				@pageChange="onTablePageChange"
			>
				<template v-slot:status="{ scope }">
					<el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
						{{ scope.row.status === 1 ? "启用" : "禁用" }}
					</el-tag>
				</template>
				<template v-slot:operation="{ scope }">
					<el-button link type="primary" @click="onTableUpdate('edit', scope.row)">修改</el-button>
					<el-button
						link
						type="danger"
						:disabled="['admin', 'common', 'test'].includes(scope.row.value)"
						@click="onTableDelete(scope.row)"
						>删除</el-button
					>
				</template>
			</HTable>
		</div>
		<HTableDialog
			ref="tableDialogRef"
			title="角色信息"
			:options="state.tableDialogOptions"
			@submit="updateTableData"
		>
			<template v-slot:permissions="{ ruleForm }">
				<HPermissionTree v-model="ruleForm.permissions" :tree-data="menuTreeData" />
			</template>
		</HTableDialog>
	</div>
</template>

<script setup lang="ts" name="role">
import { defineAsyncComponent, reactive, ref, onMounted } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { useRoutesList } from "/@/stores/routesList";
import { getRoleData } from "/@/api/demo";
import { deleteEmptyProperty } from "/@/utils/commonFunction";
import { cloneDeep } from "lodash-es";

// 引入组件
const HTableControl = defineAsyncComponent(() => import("/@/components/table/tableControl.vue"));
const HTable = defineAsyncComponent(() => import("/@/components/table/index.vue"));
const HTableDialog = defineAsyncComponent(() => import("/@/components/table/tableDialog.vue"));
const HPermissionTree = defineAsyncComponent(() => import("/@/components/permissionTree/index.vue"));

// 定义变量内容
const tableDialogRef = ref<RefType>();
const { routesList } = useRoutesList();
const state = reactive({
	// 表格配置
	tableState: <TableStateType>{
		// 配置项
		config: {
			total: 0,
			loading: false, // loading 状态
			isBorder: true, // 是否显示表格边框
			isSerialNo: true, // 是否显示表格序号
			isSelection: true, // 是否显示表格多选
			isOperate: true, // 是否显示表格操作栏
			opWidth: 150, // 表格操作栏的宽度
			isPagination: true, // 是否显示表格分页
		},
		// 表头内容
		header: [
			{ key: "label", title: "角色名称", type: "text", isCheck: true },
			{ key: "value", title: "角色标识", type: "text", isCheck: true },
			{ key: "index", title: "排序编号", type: "text", isCheck: true },
			{ key: "status", title: "角色状态", type: "customCell", slotName: "status", isCheck: true },
			{ key: "description", title: "角色描述", type: "text", isCheck: true },
			{ key: "createTime", title: "创建时间", type: "text", isCheck: true },
		],
		// 表格数据
		data: [],
		// 表格选中行
		selectedRows: [],
	},
	// 条件搜索配置
	tableSearch: <TableSearchType[]>[
		{ label: "角色名称", prop: "label", placeholder: "请输入角色名称", required: false, type: "input" },
		{ label: "角色标识", prop: "value", placeholder: "请输入角色标识", required: false, type: "input" },
		{
			label: "排序编号",
			prop: "index",
			placeholder: "请输入排序编号",
			required: false,
			type: "number",
			min: 0,
			step: 1,
			precision: 0,
		},
		{
			label: "角色状态",
			prop: "status",
			placeholder: "请选择角色状态",
			required: false,
			type: "select",
			options: [
				{ label: "启用", value: 1 },
				{ label: "禁用", value: 0 },
			],
		},
		{ label: "创建时间", prop: "createTime", placeholder: "请选择", required: false, type: "datetimeRange" },
	],
	// 通用弹窗配置
	tableDialogOptions: <TableDialogOptionsType[]>[
		{
			label: "角色名称",
			prop: "label",
			placeholder: "请输入角色名称",
			required: true,
			defaultValue: "",
			type: "input",
		},
		{
			label: "角色标识",
			prop: "value",
			placeholder: "请输入角色标识",
			required: true,
			defaultValue: "",
			type: "input",
		},
		{
			label: "排序编号",
			prop: "index",
			placeholder: "请输入排序编号",
			required: true,
			defaultValue: 0,
			type: "number",
			min: 0,
			step: 1,
			precision: 0,
		},
		{
			label: "角色状态",
			prop: "status",
			placeholder: "请选择角色状态",
			required: true,
			defaultValue: 1,
			type: "radio",
			options: [
				{ label: "启用", value: 1 },
				{ label: "禁用", value: 0 },
			],
		},
		{
			label: "角色权限",
			prop: "permissions",
			placeholder: "请选择角色权限",
			required: true,
			defaultValue: [],
			type: "slot",
		},
	],
	// 搜索参数
	params: {
		page: 1,
		limit: 20,
	},
});
const menuTreeData = ref<EmptyArrayType>([]); // 菜单树形数据

// 遍历树形数据
const traverseTreeData = (data: any[]) => {
	for (let i = 0; i < data.length; i++) {
		data[i].id = data[i].meta.id;
		data[i].label = data[i].meta.title;
		if (data[i].children && data[i].children.length > 0) {
			traverseTreeData(data[i].children);
		}
	}
	return data;
};
// 初始化树形数据
const initTreeData = async () => {
	try {
		// 菜单列表
		menuTreeData.value = traverseTreeData(cloneDeep(routesList));
	} catch (e) {
		ElMessage.error("字典数据请求失败");
	}
};
// 初始化表格数据
const initTableData = async () => {
	try {
		state.tableState.config.loading = true;
		const { code, data } = await getRoleData(state.params);
		if (code !== 200) return ElMessage.error("表格数据获取失败");
		state.tableState.data = data.data;
		state.tableState.config.total = data.total;
		state.tableState.config.loading = false;
	} catch (error) {
		console.error(error);
		ElMessage.error("表格数据请求失败");
		state.tableState.config.loading = false;
	}
};
// 更新表格数据
const updateTableData = async (type: string, data: EmptyObjectType) => {
	try {
		// const { code } = await setRole(data);
		// if (code === 200) {
		// 	ElMessage.success("操作成功");
		// 	tableDialogRef.value.closeDialog();
		// 	initTableData();
		// } else {
		// 	ElMessage.error("操作失败");
		// }
	} catch (error) {
		console.error(error);
		ElMessage.error("数据提交失败");
	}
};

// 新增&修改
const onTableUpdate = (type: string, row?: EmptyObjectType) => {
	tableDialogRef.value.openDialog(type, row);
};
// 删除
const onTableDelete = (row: EmptyObjectType) => {
	ElMessageBox.confirm(`此操作将删除【${row.name}】, 是否继续?`, "提示", {
		confirmButtonText: "删除",
		cancelButtonText: "取消",
		type: "warning",
	}).then(async () => {
		try {
			// const { code } = await deleteRole(row.id);
			// if (code === 200) {
			// 	ElMessage.success(`删除成功`);
			// 	initTableData();
			// } else {
			// 	ElMessage.error(`删除失败`);
			// }
		} catch (error) {
			console.error(error);
			ElMessage.error(`数据提交失败`);
		}
	});
};

// 条件搜索
const onTableSearch = (data: EmptyObjectType, isReset = false) => {
	state.params = deleteEmptyProperty({ ...state.params, ...data }); // 更新搜索参数
	state.params.page = 1; // 触发查询时重置页数为1
	initTableData();
};
// 分页改变
const onTablePageChange = (page: TablePageType) => {
	state.params.page = page.page;
	state.params.limit = page.limit;
	initTableData();
};

// 页面挂载后
onMounted(() => {
	initTableData();
	initTreeData();
});
</script>

<style scoped lang="scss">
.table-container {
	.table-padding {
		padding: 10px;
		.h-table {
			flex: 1;
			overflow: hidden;
		}
	}
}
</style>
